<template>
  <div class="w-full h-[100vh] flex justify-center items-center login-bg"
       v-loading="loading"
       :style="{backgroundImage:loginBg ? `url(${loginBg})` : ''}"
       element-loading-text="品牌信息加载中" >
    <div class="login_box">
      <span class="login_title">{{brandName}}</span>
      <el-form class="w-full" ref="ruleFormRef" :model="form" :rules="rules" >
        <el-form-item prop="tenantId">
          <el-input v-model="form.tenantId" style="height: 2.38rem" placeholder="企业ID"
                    :prefix-icon="User"/>
        </el-form-item>
        <el-form-item prop="username">
          <el-input v-model="form.username" style="height: 2.38rem" placeholder="账号"
                    :prefix-icon="User"/>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="form.password" type="password" style="height: 2.38rem" placeholder="密码"
                    :prefix-icon="Lock"/>
        </el-form-item>
        <el-form-item prop="code" v-if="captchaEnabled" style="margin-bottom: 1.25rem">
          <div style="width: 100%;" class="fixed-row">
            <el-input
              v-model="form.code"
              auto-complete="off"
              placeholder="验证码"
              style="flex: 1;height: 2.38rem"
              :prefix-icon="ChatLineSquare"
            >
            </el-input>
            <div class="login-code">
              <img :src="codeUrl" @click="getCode" class="login-code-img"/>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="loginLoading"
            class="w-full"
            @click="loginHandler(ruleFormRef)"
            style="height: 2.38rem"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { useUserStore } from '@/stores/modules/user'
  import { type FormInstance, type FormRules } from 'element-plus'
  import {getCodeImg,getPinLogingBg} from '~/api/login'
  import {getInfo} from '~/api/public'
  import {User,Lock,ChatLineSquare} from '@element-plus/icons-vue'
  import { getItem, setItem } from '~/utils/index'
  import {screenStore} from '~/stores/modules/screen'
  definePageMeta({
    title: '登录',
    hideInMenu: true
  })
  useHead({
    title: '登录'
  })
  const scrStore = screenStore()
  const userStore = useUserStore()
  const captchaEnabled = ref(true)
  const loading = ref(false)
  const brandName = ref('')
  const loginBg = ref('')
  const codeUrl = ref('')
  onMounted(() => {
    getCode()
    sessionStorage.removeItem('showLogin')
    loading.value = true
    const id = getItem('pinpaiId')
    getPinLogingBg(id).then(res => {
      if(res.code == 200){
        if(res.data){
          loading.value = false
          loginBg.value = JSON.parse(res.data.imageUrl)[0].url
          brandName.value = res.data.brandName
          scrStore.brandName = res.data.brandName
          form.value.tenantId = getItem('tenantId')
        }
        else{
          ElMessage.error('暂无品牌信息！')
        }

      }
      else{
        loading.value = false
      }
    }).catch(()=>{
      loading.value = false
    })
  })
  const router = useRouter()
  /** 登录表单 */
  const ruleFormRef = ref<FormInstance>()
  const form = ref({
    tenantId:'',
    username: '',
    password: '',
    code: "",
    uuid:'',
  })
  const rules = reactive<FormRules<{ username: string; password: string,code:string }>>({
    tenantId:[{ required: true, message: '企业ID不能为空', trigger: 'blur' }],
    username: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
    password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
    code:[{required:true,message:'请填写验证码',trigger:'blur'}],
  })

  const loginLoading = ref(false)
  function getCode() {
    getCodeImg().then(res => {
      captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
      if (captchaEnabled.value) {
        codeUrl.value = "data:image/gif;base64," + res.img;
        form.value.uuid = res.uuid;
      }
      else{
        ElMessage.error(res.msg)
        getCode()
      }
    });
  }
  /** 点击登录按钮 */
  const loginHandler = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        loginLoading.value = true
        userStore.Login(form.value)
          .then(() => {

            ElMessage.success('登录成功')
            router.push('/')
            // 获取个人信息 和 获取菜单
            nextTick(()=>{
              getInfo().then(result => {
                if(result.code == 200){
                  scrStore.roles = result.roles
                  scrStore.user = result.user
                }
                else{
                  ElMessage.error(result.msg)
                }
              })
            })
          }).catch((err)=>{
            ElMessage.error(err)
          getCode()
        })
          .finally(() => {
            loginLoading.value = false
          })
      } else {
        console.log('error submit!', fields)
      }
    })
  }
  useKeyboardEvt(13, () => loginHandler(ruleFormRef.value))
</script>

<style scoped lang="less">
  .login-bg{
    background-size: cover; /* 关键属性 */
    background-position: center; /* 关键属性 */
  }
  .login_box {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 1.25rem;
    z-index: 999;
    width: 25rem;
    background-color: #fff;
    backdrop-filter: blur(20px); //毛玻璃属性
    border-radius: 1rem;
    overflow: hidden;

    .login_title {
      margin-bottom: 1.25rem;
      font-size: 1rem;
      font-weight: 500;
      color: #707070;
    }
  }

  .login-code{
    margin-left: 0.63rem;
  }
  .login-code-img {
    height: 2.38rem
  }
</style>
